<template>
    <div class="work-new-div" v-loading="isLoading">
        
        <el-form ref="workInfo" :model="workInfo" label-width="100px">
            <el-form-item label="所属课程：" class="workinfo-item"  >
                 <el-select v-model="workInfo.courseId" placeholder="请选择课程的名字">
                    <el-option
                    v-for="courseInfo in myCouseInfos"
                    :key="courseInfo.courseId"
                    :label="courseInfo.courseName"
                    :value="courseInfo.courseId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="作业类型：" class="workinfo-item">
                <el-tag>选择题无需老师批改，文本题需要老师批改</el-tag>
                <el-radio v-model="workInfo.workType" :label="1">文本题</el-radio>
                <el-radio v-model="workInfo.workType" :label="2">选择题</el-radio>
            </el-form-item>

            <el-form-item label="作业名字：" class="workinfo-item">
                <el-input v-model="workInfo.workName" placeholder="建议使用课后作业-1这样，请不要太长"></el-input>
            </el-form-item>

            <el-form-item label="作业分数：" class="workinfo-item">
                <el-input type="number" v-model="workInfo.workScore"></el-input>
            </el-form-item>

            <el-form-item label="结束时间：" class="workinfo-item">
                <el-date-picker
                v-model="workInfo.endTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="题干内容：" >
                <el-radio v-model="workInfo.contentType" :label='1'>上传文本</el-radio>
                <el-radio v-model="workInfo.contentType" :label='2'>上传图片</el-radio>

                <editor @editorContent="getContent"  v-if="workInfo.contentType == 1"></editor>
                <el-upload
                        v-if="workInfo.contentType == 2"
                        class="avatar-uploader"
                        action
                        :show-file-list="false"
                        v-model="workInfo.workImgUrl"
                        :before-upload="beforeAvatarUpload"
                        :http-request="getImgPutUrlFromSts"
                        >
                        <img v-if="workInfo.workImgUrl" :src="workInfo.workImgUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>

            </el-form-item>

            <el-form-item label="设置选项："  v-if="workInfo.workType == 2">
                <el-tag type="info">最多支持17个, 如果不够，请联系系统服务者进行添加</el-tag>
                <br>
                <el-button style="margin-top:1%;" @click="addCheck">+ 添加选项</el-button>
                <el-button @click="changeCheckType">{{checkTypeLabel}}</el-button>
                <el-button @click="changeHalfRight" v-if="workInfo.isMuitlSelect">{{halfRightLabel}}</el-button>
                <el-tag style="margin-left:2%;" :type="workInfo.startHalfRightGetScore?'success':'danger'" v-if="workInfo.isMuitlSelect">
                    {{workInfo.startHalfRightGetScore?'已开启半对得分':'已关闭半对得分'}}
                </el-tag>
                
                <div class="work-check-item" id="checkinfo">
                        <div  v-for="checkinfo,index in workInfo.checkInfos" 
                        :key="index" style="margin-top:1%;">

                            {{checkinfo.label}} : 
                            <el-input class="check-input" v-model="checkinfo.content"></el-input>
                            <el-radio style="margin-left:2%;" border 
                            v-if="!workInfo.isMuitlSelect"
                            @change="changeTheTrueCheck(checkinfo.label)"
                            v-model="workInfo.trueCheck" :label='checkinfo.label'>设为正确答案</el-radio>

                            <el-checkbox border style="margin-left:2%" 
                            v-if="workInfo.isMuitlSelect"
                            :label='checkinfo.label' v-model="workInfo.checkList">设为正确答案</el-checkbox>
                        </div>

                </div>


            </el-form-item>
            <el-form-item>
                <el-button @click="createWork">开始创建</el-button>
            </el-form-item> 
        </el-form>

        <!-- <editor></editor> -->
    </div>
</template>

<script>
import Editor from '../../components/Editor.vue'
import * as COURSEAPI from '../../api/course/index'
import * as WORKAPI from '../../api/work/index'
import * as FILEAPI from '../../api/file/index'
import UUID from 'uuidjs';

export default {
  components: { Editor },
    data() {
        return {
            checkLabels:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                        'K', 'L', 'M', 'N', 'O', 'P', 'Q'],
            checkLabelIndex: 0,
            checkTypeLabel:"切换为多选",
            halfRightLabel:'开启半对得分',
            isLoading:false,
            workInfo: {
                workName:"",
                workScore: 5,
                workType: 1, //1是文本，2是选择
                contentType: 1,
                isMuitlSelect:false,
                content: "",
                trueCheck:'A',
                endTime:"",
                workImgUrl:"",
                startHalfRightGetScore: false,
                checkList:['A'],
                checkInfos:[
                    {label:"A", 'content':'', isTrueCheck:true}
                ],
                courseId:''
            },
            myCouseInfos: [
            ]
        }
    },
    methods: {
        changeTheTrueCheck(label){
            console.log(label)
            this.workInfo.checkInfos.forEach(checkInfo => {
                if(checkInfo.label === label) {
                    checkInfo.isTrueCheck = true
                }else {
                     checkInfo.isTrueCheck = false
                }
            })
        },
        addCheck() {
            let newLabel = this.checkLabels[++this.checkLabelIndex]
            this.workInfo.checkInfos.push(
                {
                    label: newLabel,
                    content: "",
                    isTrueCheck: false,
                }
            )
        },
        createWork() {
            this.isLoading = true
            // console.log(this.workInfo.checkInfos)
            WORKAPI.createWork(this.workInfo).then(res => {
                if(res.code == 200) {
                    this.$message({
                        message: '作业发布成功',
                        type: 'success'
                    });
                }else {
                    this.$message({
                        message: '作业发布失败：' + res.data.error,
                        type: 'error'
                    });
                }
                this.isLoading = false
            }).catch(err => {
                this.$message.error('网络错误')
                this.isLoading = false
            })
        },
        getContent(data) {
            this.workInfo.content = data
        },
        handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        changeCheckType() {
            if(this.workInfo.isMuitlSelect) {
                this.workInfo.isMuitlSelect = false
                this.checkTypeLabel = '切换为多选'
            }else {
                this.workInfo.isMuitlSelect = true
                this.checkTypeLabel = '切换为单选'
            }
        },
        changeHalfRight() {
            if(this.workInfo.startHalfRightGetScore) {
                this.workInfo.startHalfRightGetScore = false
                this.halfRightLabel = '开启半对得分'

            }else {
                //当前状态为
                this.workInfo.startHalfRightGetScore = true

                this.halfRightLabel = '关闭半对得分'
            }
        },
        getMyCouses() {        
            COURSEAPI.getMyCourse().then(res => {
                let data = res.data
                let courseInfos = data.courses

                courseInfos.forEach(courseInfo => {
                    this.myCouseInfos.push({
                        courseId:courseInfo.courseId,
                        courseName:courseInfo.courseName
                    })
                });

            }).catch(err => {
                this.$message.error('网络错误')
            }) 
        },
        getImgPutUrlFromSts(option) {
            let fileName = UUID.generate()
            let fileType = option.file.type.split("/")[1]
            FILEAPI.getImgUrl(fileName, fileType).then(res => {

                let url = res.data.URL

                const oReq = new XMLHttpRequest();
                oReq.open('PUT', url, true);
                oReq.setRequestHeader("Content-Type", "application/octet-stream")
                oReq.setRequestHeader("x-oss-meta-author", "nothing")
                oReq.send(option.file);
                oReq.onload = () => {
                    this.workInfo.workImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                };
            }).catch((error) => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: error,
                });
            });
        },
    },
    mounted() {
        this.getMyCouses()
    }
}
</script>

<style>
.work-new-div {
    margin: 2%;
    width: 96%;
}

.workinfo-item {
    width: 370px;
}

.work-check-item {
    display: flex;
    min-width: 100px;
    margin-top: 1%;
    flex-direction: column;
}

/* .work-check-item >  el-radio{
    width: 50px;
} */

.check-input {
    width: 200px;
    margin-left: 2%;
}

.el-select .el-input {
    width: 220px;
}

</style>